import COS from 'cos-nodejs-sdk-v5'

// 实例化COS
const cos = new COS({
    SecretId: process.env.SecretId,
    SecretKey: process.env.SecretKey
});

// 存储桶信息
const Bucket = process.env.Bucket
const Region = process.env.Region


// 将文件存到云
export const upload = async (Key, FilePath) => {
    return await cos.uploadFile({
        Bucket,
        Region,
        Key,
        FilePath,
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        }
    })
}
// 获取存储桶内所有对象
export const getBucket = async (Key) => {
    return await cos.getBucket({
        Bucket,
        Region,
        Key,
    })
}

// 获取对象地址
const getPromiseObjectUrl = async (options) => {
    return new Promise((resolve, reject) => {
        cos.getObjectUrl(options, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data.Url);
            }
        })
    })
}

// 方法
export const getUrl = async (Key, Expired = 600) => {
    try {
        return await getPromiseObjectUrl({
            Key,
            Bucket,
            Region,
            Expired
        });
    } catch (error) {
        console.error(error);
        throw error;
    }
};